import { forwardRef, useMemo } from 'react';
import { connect, mapProps } from '@formily/react';
import { Switch } from 'antd';
import { getMessage } from '@inbiz/react';
import { defaultProps } from '../../designer/schema';
import './style.less';

type IProps = {
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  onChange?: any;
  emit?: () => void;
  value?: number;
  readOnly?: boolean;
  disabled?: boolean;
} & typeof defaultProps;

const EformSwitchContent = forwardRef((props: IProps, ref) => {
  const { callBackEvents, emit, ...other } = props;

  // 处理开关值 （0：关闭，1：打开）
  const formatValue = useMemo(() => {
    if (props.value == 1) {
      return true;
    } else if (props.value == 0) {
      return false;
    }
    return;
  }, [props.value]);

  const onChange = (value: any) => {
    props.onChange(value ? 1 : 0);
  };
  return (
    <div style={{ minWidth: 130 }}>
      <Switch
        className={'EformSwitch'}
        checkedChildren={props.checkedChildren}
        unCheckedChildren={props.unCheckedChildren}
        disabled={props.readOnly || props.disabled}
        checked={formatValue}
        onChange={onChange}
      />
    </div>
  );
});
EformSwitchContent.displayName = 'EformSwitchContent';

(
  EformSwitchContent as typeof EformSwitchContent & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props:any): 0 | 1 => {
  return props.defaultChecked ? 1 : 0;
};

export default connect(
  EformSwitchContent,
  mapProps((props: IProps) => {
    const other = props;
    other.checkedChildren = getMessage(props.checkedChildren);
    other.unCheckedChildren = getMessage(props.unCheckedChildren);
    return { ...other };
  }),
);

export type { IProps };
